package com.team.childapp.ui.contacts

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import android.view.KeyEvent
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.bumptech.glide.Glide
import com.huanguo.dashboard.base.adapter.KotlinDataAdapter
import com.mig35.carousellayoutmanager.CarouselLayoutManager
import com.mig35.carousellayoutmanager.CarouselLayoutManager.HORIZONTAL
import com.mig35.carousellayoutmanager.CarouselZoomPostLayoutListener
import com.mig35.carousellayoutmanager.CenterScrollListener
import com.mig35.carousellayoutmanager.DefaultChildSelectionListener
import com.team.childapp.R
import com.team.childapp.base.activity.BaseActivity
import com.team.childapp.base.listener.ICallBackResultListener
import com.team.childapp.bean.constants.ConstantsBean
import com.team.childapp.databinding.ActivityContactsBinding
import com.team.childapp.http.ConstantsLogical
import com.team.childapp.listener.CustomerCenterScrollListener
import com.team.childapp.listener.CustomerContactsScrollListener
import com.team.childapp.ui.ai.AiGenerateTextByImageActivity
import com.team.childapp.ui.ai.AiMessageActivity
import com.team.childapp.ui.setting.SettingActivity
import com.team.childapp.ui.setting.SettingInformationActivity
import com.team.childapp.ui.studygarden.StudyGardenActivity
import com.team.childapp.util.JsonSerializer
import com.team.childapp.util.LogUtils
import java.util.Locale


/**
 * Create on: 2024/12/30
 * by Mr.Zhu
 * Description: TODO
 */
class ContactsActivity: BaseActivity<ActivityContactsBinding>(R.layout.activity_contacts) {
    private var dataAdapter: KotlinDataAdapter<ConstantsBean>? = null
    private val list = arrayListOf<ConstantsBean>()
    private var selectedContact: ConstantsBean? = null
    private val REQUEST_CALL_PERMISSION = 10086
    private var currentSelectedIndex = 0

    override fun initData() {
        mBinding.imageBack.setOnClickListener {
            finish()
        }
        mBinding.imageAddContacts.setOnClickListener {
            jumpToModifyContactsActivity(null)
        }
        mBinding.imageCallPhone.setOnClickListener {
            selectedContact?.let {
                val phoneNumber = it.telephone.trim()
                if (phoneNumber.isEmpty()) {
                    Toast.makeText(this@ContactsActivity, "无效的电话号码", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                checkAndRequestCallPermission()
            } ?: run {
                Toast.makeText(this@ContactsActivity, "请选择一个联系人", Toast.LENGTH_SHORT).show()
            }

        }
    }

    override fun onResume() {
        super.onResume()
        getConstantsList()
    }

    //检查拨打电话权限
    private fun checkAndRequestCallPermission() {
        if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CALL_PHONE), REQUEST_CALL_PERMISSION)
        } else{
            makePhoneCall()
        }
    }

    //拨打电话
    private fun makePhoneCall() {
        selectedContact?.let {
            val phoneNumber = it.telephone.trim()
            val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$phoneNumber"))
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            } else {
                Toast.makeText(this@ContactsActivity, "无法拨打电话", Toast.LENGTH_SHORT).show()
            }
        } ?: run {
            Toast.makeText(this@ContactsActivity, "请选择一个联系人", Toast.LENGTH_SHORT).show()
        }
    }

    private fun jumpToModifyContactsActivity(contact: ConstantsBean?) {
        val intent = Intent(this, ModifyContactsActivity::class.java)
        if (contact != null) {
            intent.putExtra("contact",contact)
        }
        startActivity(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CALL_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                makePhoneCall()
            } else {
                Toast.makeText(this, "无法拨打电话，权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun getConstantsList(){
        ConstantsLogical.getInstanceLogin().requestConstants(this,
            object :ICallBackResultListener {
                override fun onCallBack(result: Any?) {
                    val bean = result as ConstantsBean
                    list.addAll(bean.data)
                    initAdapter()
                }
            })
    }

    private fun initAdapter(){
        // 配置 CarouselLayoutManager
        val layoutManager = CarouselLayoutManager(HORIZONTAL, true).apply {
            maxVisibleItems = 3
            setPostLayoutListener(CarouselZoomPostLayoutListener())
            addOnItemSelectionListener { adapterPosition: Int ->
//                mBinding.tvName.text = list[adapterPosition].name
                selectedContact = list[adapterPosition]
            }
        }
        // enable center post touching on item and item click listener
        DefaultChildSelectionListener.initCenterItemListener({ recyclerView, carouselLayoutManager, v ->
            val position = recyclerView.getChildLayoutPosition(v)
            val msg = String.format(Locale.US, "Item %1\$d was clicked", position)
            Toast.makeText( this@ContactsActivity,msg, Toast.LENGTH_SHORT).show()
        }, mBinding.contactsRecyclerView, layoutManager)

        mBinding.contactsRecyclerView.isFocusableInTouchMode=false
        mBinding.contactsRecyclerView.isFocusable=false
        mBinding.contactsRecyclerView.apply {
            this.layoutManager = layoutManager
            setHasFixedSize(true)
            addOnScrollListener(CustomerContactsScrollListener(this@ContactsActivity,list))
            adapter = KotlinDataAdapter.Builder<ConstantsBean>()
                .setLayoutId(R.layout.adapter_status_light_item)
                .setData(list)
                .addBindView { itemView, itemData , position ->
                    itemView.isFocusableInTouchMode=false
                    itemView.isFocusable = false
                    itemView.background = null
                    if (position % 2 == 0) {
                        itemView.findViewById<ImageView>(R.id.iv_icon).background = ResourcesCompat.getDrawable(resources, R.mipmap.icon_yellow_bg, null)
                    } else {
                        itemView.findViewById<ImageView>(R.id.iv_icon).background = ResourcesCompat.getDrawable(resources, R.mipmap.icon_blue_bg, null)
                    }
//                    itemView.findViewById<ImageView>(R.id.iv_icon).background = itemData.avatar;
                    itemView.findViewById<TextView>(R.id.tv_name).text = itemData.name
                    itemData.avatar?.let {
                        if (TextUtils.isEmpty(it)) {
                            return@let
                        }
                        var resource= R.mipmap.icon_head_baba//爸爸
                        if (TextUtils.equals(it, "1")) {//妈妈
                            resource = R.mipmap.icon_head_mam
                        } else if (TextUtils.equals(it, "2")) {//哥哥
                            resource = R.mipmap.icon_head_gege
                        }else if (TextUtils.equals(it, "3")) {//姐姐
                            resource = R.mipmap.icon_head_jiejie
                        }else if (TextUtils.equals(it, "4")) {//爷爷
                            resource = R.mipmap.icon_head_yeye1
                        }else if (TextUtils.equals(it, "5")) {
                            resource = R.mipmap.icon_head_yeye2
                        }else if (TextUtils.equals(it, "6")) {//奶奶
                            resource = R.mipmap.icon_head_nainia1
                        }else if (TextUtils.equals(it, "7")) {
                            resource = R.mipmap.icon_head_nainai2
                        }
                        itemView.findViewById<ImageView>(R.id.image_head_local)?.setImageResource(resource)
                    }
                    itemView.findViewById<ImageView>(R.id.image_delete).setOnClickListener {
                        // 启动 ContactsActivity 并传递数据
                        jumpToModifyContactsActivity(itemData)
                    }
                }
                .create()
        }
    }

    // 重写 onKeyDown 方法
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        setImageSelected(currentSelectedIndex, false)
        return when (keyCode) {

            KeyEvent.KEYCODE_DPAD_UP -> {
//                LogUtils.showLog("当前的按键为KEYCODE_DPAD_UP，Index的值为 ：$currentSelectedIndex")

                if (currentSelectedIndex<1) {
                    currentSelectedIndex = list.size-1
                } else {
                    currentSelectedIndex = currentSelectedIndex -1
                }
                setImageSelected(currentSelectedIndex, true)
                true // 表示事件已处理
            }
            KeyEvent.KEYCODE_DPAD_DOWN -> {
//                LogUtils.showLog("当前的按键为KEYCODE_DPAD_DOWN，Index的值为 ：$currentSelectedIndex")
//
                if (currentSelectedIndex>list.size-2) {
                    currentSelectedIndex = 0
                } else {
                    currentSelectedIndex = currentSelectedIndex + 1
                }

                setImageSelected(currentSelectedIndex, true)
                true // 表示事件已处理
            }
            KeyEvent.KEYCODE_ENTER -> {
//                when(currentSelectedIndex) {
//
//                }
                true
            }



            else -> super.onKeyDown(keyCode, event) // 其他按键交给系统处理

        }


    }
    private fun setImageSelected(index: Int, selectEnale: Boolean) {
//        mBinding.tv_name.text = list[index].name
        selectedContact = list[index]

        mBinding.contactsRecyclerView.smoothScrollToPosition(index)
        // 禁用 RecyclerView 子项的焦点
        mBinding.contactsRecyclerView.isFocusableInTouchMode = false
        mBinding.contactsRecyclerView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS


    }
}